package com.ruoyi.procurement.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.WXShiroUtils;
import com.ruoyi.company.domain.Company;
import com.ruoyi.company.domain.CompanyOther;
import com.ruoyi.company.mapper.CompanyMapper;
import com.ruoyi.company.service.ICompanyInvoiceService;
import com.ruoyi.company.service.ICompanyOtherServer;
import com.ruoyi.information.domain.Information;
import com.ruoyi.information.service.InformationService;
import com.ruoyi.procurement.domain.ProcurementModel;
import com.ruoyi.procurement.domain.ProcurementOrder;
import com.ruoyi.procurement.service.ProcurementServer;
import com.ruoyi.product.domain.Product;
import com.ruoyi.product.domain.ProductModel;
import com.ruoyi.product.service.ProductServer;
import com.ruoyi.productProof.domain.ProductProof;
import com.ruoyi.productProof.service.ProductProofService;
import com.ruoyi.purchase.domain.PurchaseOrder;
import com.ruoyi.purchase.service.PurchaseOrderService;
import com.ruoyi.sale.domain.SaleGoodsModel;
import com.ruoyi.sale.domain.SaleGoodsOrder;
import com.ruoyi.sale.service.ISaleGoodsService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.warehousing.domain.Warehousing;
import com.ruoyi.warehousing.service.WarehousingService;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 采购入库管理
 */
@RestController
@RequestMapping("/business/procurement")
public class ProcurementController extends BaseController {

    @Autowired
    ICompanyOtherServer iCompanyOtherServer;
    @Autowired
    WarehousingService warehousingService;
    @Autowired
    CompanyMapper companyMapper;
    private String prefix = "procurement";
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ICompanyInvoiceService invoiceService;
    @Autowired
    private ProcurementServer procurementServer;
    @Autowired
    private InformationService informationService;
    @Autowired
    private PurchaseOrderService purchaseOrderService;
    @Autowired
    private ProductServer productServer;
    @Autowired
    private ISaleGoodsService iSaleGoodsService;

    /**
     * 查询采购订单入库信息
     */
    @RequiresPermissions("business:procurement:view")
    @GetMapping()
    public String operlog() {
        return prefix + "/list";
    }

    /**
     * 查询采购订单入库信息列表
     */
    @RequiresPermissions("business:procurement:list")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestParam(value = "beginTime", required = false) String beginTime,
                              @RequestParam(value = "endTime", required = false) String endTime,
                              @RequestParam(value = "deptName", required = false) String deptName,
                              @RequestParam(value = "procurementStatus", required = false) String procurementStatus,
                              @RequestParam(value = "procurementWarehousingName", required = false) String procurementWarehousingName) {
        ProcurementOrder procurement = new ProcurementOrder();
        procurement.setBeginTime(beginTime);
        procurement.setEndTime(endTime);
        procurement.setDeptName(deptName);
        procurement.setProcurementStatus(procurementStatus);
        procurement.setProcurementWarehousingName(procurementWarehousingName);
        startPage();
        procurement.setDeptId(SecurityUtils.getLoginUser().getUser().getCompanyId());
        List<ProcurementOrder> list = procurementServer.selectProcurementList(procurement);
        return getDataTable(list);
    }

    /**
     * 查看入库订单
     */
    @GetMapping("/look/{procurementWarehousingId}")
    public Map<String, Object> look(@PathVariable("procurementWarehousingId") Long procurementWarehousingId, ModelMap mmap) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Map<String, Object> resMap = new HashMap<>();
        mmap.put("supplier", userService.selectSupplierById(sysUser.getCompanyId()));
        mmap.put("user", userService.selectSalesmanList(sysUser.getCompanyId()));
        ProcurementOrder procurementOrders = new ProcurementOrder();
        procurementOrders.setProcurementWarehousingId(procurementWarehousingId);
        //查询产品入库信息
        ProcurementOrder procurementOrder1 = procurementServer.selectProcurementBy(procurementOrders);
        //产品入库子集属性
        List<ProcurementModel> procurementModels = procurementServer.selectProcurementModelById(procurementWarehousingId);
        if (procurementServer.selectProcurementModelById(procurementWarehousingId).size() != 0) {
            resMap.put("procurementOrder", procurementOrder1);
        } else {
            procurementOrder1.setProcurementModelList(procurementModels);
            resMap.put("procurementOrder", procurementOrder1);
        }
        return resMap;
    }

    @GetMapping("/look/null")
    @ResponseBody
    public Boolean look(ModelMap mmap) {
        return true;
    }

    /**
     * 修改保存产品信息
     */
    @Log(title = "修改保存产品资料", businessType = BusinessType.UPDATE)
    @PostMapping("/editInformation")
    @ResponseBody
    public AjaxResult editInformation(@Validated ProcurementOrder procurementOrder) {
        return toAjax(informationService.updateInformationList(procurementOrder));
    }

    /**
     * 采购入库订单审核
     * @param procurementWarehousingId 采购入库单ID
     * @param procurementStatus 审核状态. 0:回退,1:通过,2:驳回
     * @return 结果
     */
    @GetMapping("/auditSale")
    @ResponseBody
    public AjaxResult auditSale(@RequestParam(value = "procurementWarehousingId", required = false) Long procurementWarehousingId,
                                @RequestParam(value = "procurementStatus", required = false) String procurementStatus) {
        ProcurementOrder procurementOrder = new ProcurementOrder();
        procurementOrder.setProcurementWarehousingId(procurementWarehousingId);
        procurementOrder.setProcurementStatus(procurementStatus);
        return toAjax(procurementServer.auditSale(procurementOrder));
    }

    /**
     * 选择销货单界面
     */
    @GetMapping("/selectSalegoods")
    public String selectSalegoods() {
        return prefix + "/selectSalegoods";
    }

    /**
     * 选择销货订单列表 post
     */
    @GetMapping("/selectSalegoodsList")
    @ResponseBody
    public Map<String, Object> showlist(@RequestParam(value = "beginTime", required = false) String beginTime,
                                        @RequestParam(value = "endTime", required = false) String endTime,
                                        @RequestParam(value = "deptName", required = false) String deptName) {

        Map<String, Object> resMap = new HashMap<>();
        SaleGoodsOrder saleGoodsOrder = new SaleGoodsOrder();
        saleGoodsOrder.setBeginTime(beginTime);
        saleGoodsOrder.setEndTime(endTime);
        saleGoodsOrder.setDeptName(deptName);
        startPage();
        saleGoodsOrder.setCustomerId(SecurityUtils.getLoginUser().getUser().getCompanyId());
        saleGoodsOrder.setSaleGoodsStatus("1");
        saleGoodsOrder.setIsWarehousingOrder(0);
        List<SaleGoodsOrder> list = iSaleGoodsService.selectSaleGoodsLists(saleGoodsOrder);
        for (SaleGoodsOrder saleGoodsOrder1 : list) {
            List<SaleGoodsModel> saleGoodsModel = saleGoodsOrder1.getSaleGoodsModels();
            for (SaleGoodsModel value : saleGoodsModel) {
                if (value.getUnit().equals("盒") || value.getUnit() == "盒") {
                    if (value.getBacknum() != 0 && value.getSurplusnum() != 0) {
                        int b = value.getBacknum() / value.getFactor().intValue();
                        int c = value.getSurplusnum() / value.getFactor().intValue();
                        value.setSurplusnum(c);
                        value.setBacknum(b);
                    }
                }
            }
        }
        resMap.put("list", list);
        return resMap;
    }

    protected TableDataInfo getDataTable2(List<?> list) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(list);
        rspData.setTotal(list.size());
        return rspData;
    }

    /**
     * 根据purchaseid 查询 采购订单编号
     *
     * @return
     */
    @PostMapping("/selectSalegoodsById")
    @ResponseBody
    public JSONObject selectPurchaseById(@RequestParam("saleGoodsId") Long saleGoodsId) {
        JSONObject jsonObject = new JSONObject();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("saleGoodsId", saleGoodsId);
        hashMap.put("isWarehousingOrder", 0);
        SaleGoodsOrder saleGoodsOrder = iSaleGoodsService.selectSaleGoodsByIds(hashMap);
        List<SaleGoodsModel> saleGoodsModel = saleGoodsOrder.getSaleGoodsModels();
        for (SaleGoodsModel value : saleGoodsModel) {
            if (value.getUnit().equals("盒")) {
                List<Integer> list1 = procurementServer.selectProductType(value.getProductType());
                int a = list1.get(0);
                if (a != 0) {
                    int c = value.getSurplusnum() / a;
                    value.setSurplusnum(c);
                }
            }
        }
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(saleGoodsOrder);
        jsonObject.put("saleGoodsOrder", jsonArray);
        return jsonObject;
    }

    /**
     * 选择销货单 子表的数据
     */
    @GetMapping("/selectSalegoodsLists")
    @ResponseBody
    public TableDataInfo selectSalegoodsLists(@RequestParam("saleGoodsId") Long saleGoodsId) {
        startPage();
        HashMap hashMap = new HashMap();
        hashMap.put("saleGoodsId", saleGoodsId);
        hashMap.put("isWarehousingOrder", 0);
        hashMap.put("deptId", SecurityUtils.getLoginUser().getCompanyId());
        List<SaleGoodsModel> saleGoodsModel = iSaleGoodsService.selectSaleGoodsModelWarehousingOrderIsSuppByMap(hashMap);
        for (SaleGoodsModel value : saleGoodsModel) {
            if (value.getUnit().equals("盒")) {
                if (value.getBacknum() != 0) {
                    value.setBacknum(value.getBacknum() / value.getFactor().intValue());
                }
                if (value.getSurplusnum() != 0) {
                    value.setSurplusnum(value.getSurplusnum() / value.getFactor().intValue());
                }
            }
        }
        return getDataTable(saleGoodsModel);
    }

    /**
     * 添加 采购订单入库信息
     */
    @GetMapping("/selectInformation")
    public Map<String, Object> add() {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Map<String, Object> resMap = new HashMap<>();
        //使用SimpleDateFormat的parse()方法生成Date
        SimpleDateFormat a = new SimpleDateFormat("yyyy-MM-dd");
        Date dates = null;
        try {
            dates = a.parse(a.format(new Date()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        resMap.put("procurementWarehousingName", purchaseOrderService.orderNum(dates, 0));
        //用户主键
        resMap.put("sysUser", sysUser.getDeptId());
        //供应商
        resMap.put("supplier", userService.selectSupplierById(sysUser.getCompanyId()));
        //用户
        resMap.put("user", userService.selectSalesmanList(sysUser.getCompanyId()));
        //税率
        Company company = companyMapper.selectByCompanyId(sysUser.getCompanyId());
        resMap.put("taxRate", company.getTaxRate());
        return resMap;
    }

    /**
     * 查询项目--跳转页面
     */
    @GetMapping("selectProductModelList")
    public String selectProductModelList(ModelMap mmap) {
        Long supplierId = ShiroUtils.getSysUser().getCompanyId();
        mmap.put("supplierId", supplierId);
        return prefix + "/selectProductModelLists";
    }

    /**
     * 下拉表格
     */
    @GetMapping("/selectTableRow")
    @ResponseBody
    public JSONObject tableSelect(@RequestParam(value = "productType", required = false) String productType) {
        Long supplierId = SecurityUtils.getLoginUser().getUser().getCompanyId();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("msg", "");
        Map map = new HashMap<String, Object>();
        if (supplierId != null & !"".equals(supplierId)) {
            map.put("deptId", supplierId);
            map.put("productType", productType);
            map.put("allowSharing", null);
        }
        //查询产品信息，定义信息新的jsonArray数组
        List<Product> products = purchaseOrderService.selectProducts(map);
        JSONArray array = new JSONArray();
        for (Product product : products) {
            //判断产品型号规格信息
            if (product.getProductModel().size() != 0) {
                List<ProductModel> productModels = product.getProductModel();
                for (ProductModel productModel : productModels) {
                    JSONObject obj = new JSONObject();
                    obj.put("productId", product.getProductId());
                    obj.put("productName", product.getProductName());
                    obj.put("modelNo", productModel.getModelNo());
                    obj.put("modelCode", productModel.getModelCode());
                    obj.put("productType", productModel.getProductType());
                    obj.put("warehousingNum", productModel.getWarehousingNum());
                    obj.put("unit", productModel.getUnit());
                    obj.put("factor", productModel.getFactor());
                    obj.put("selectId", product.getSelectId());
                    array.add(obj);
                }
            }
        }
        jsonObject.put("data", array);
        return jsonObject;
    }

    /**
     * 查询产品注册证
     *
     * @param productId 产品主键
     * @return 结果
     */
    @GetMapping("/selectProductProof")
    @ResponseBody
    public Map<String, Object> selectProductProof(
            @RequestParam(value = "productId", required = false) Long productId,
            @RequestParam(value = "selectId", required = false) Long selectId,
            @RequestParam(value = "batch", required = false) String batch,
            @RequestParam(value = "productType", required = false) String productType) {

        Map<String, Object> resMap = new HashMap<>();
        Warehousing warehousing = new Warehousing();
        Map map = new HashMap<String, Object>();
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        map.put("productId", productId);
        map.put("selectId", selectId);
        map.put("deptId", sysUser.getCompanyId());

        warehousing.setBatch(batch);
        warehousing.setProductId(productId);
        warehousing.setSelectId(productId);
        warehousing.setProductType(productType);
        warehousing.setDeptId(sysUser.getCompanyId());
        Warehousing warehousings = warehousingService.selectWarehousing(warehousing);
        if (warehousings != null) {
            resMap.put("warehousings", warehousings);
        } else {
            Product productProof = productServer.selectProductProofByMap(map);
            productProof.setProductionDate("");
            productProof.setEffectiveDate("");
            resMap.put("warehousings", productProof);
        }
        return resMap;
    }

    /**
     * 查询产品资料
     *
     * @param deptId      公司主键
     * @param batch       产品批号
     * @param productType 产品规格型号
     * @return 结果
     */
    @PostMapping("/selectInformation")
    @ResponseBody
    public Information selectInformation(@RequestParam(value = "deptId", required = false) Long deptId, @RequestParam(value = "batch", required = false) String batch, @RequestParam(value = "productType", required = false) String productType) {
        Map map = new HashMap<String, Object>();
        if (deptId == null) {
            deptId = ShiroUtils.getSysUser().getCompanyId();
        }
        if (deptId != null && !"".equals(batch)) {
            map.put("deptId", deptId);
            map.put("batch", batch);
            map.put("productType", productType);
        }
        Information information = informationService.selectInformationByMap(map);
        return information;
    }

    /**
     * 查询库存中的生产日期和失效日期
     *
     * @param deptId      公司主键
     * @param batch       产品批号
     * @param productType 产品规格型号
     * @param productId   产品主键
     * @return 结果
     */
    @PostMapping("/selectWarehousing")
    @ResponseBody
    public AjaxResult selectWarehousing(@RequestParam(value = "deptId") Long deptId, @RequestParam(value = "productId") Long productId, @RequestParam(value = "batch") String batch, @RequestParam(value = "productType") String productType) {
        Warehousing warehousing = new Warehousing();
        if (deptId == null) {
            warehousing.setDeptId(SecurityUtils.getLoginUser().getUser().getCompanyId());
        } else {
            warehousing.setDeptId(deptId);
        }
        warehousing.setBatch(batch);
        warehousing.setProductId(productId);
        warehousing.setProductType(productType);
        Warehousing warehousings = warehousingService.selectWarehousing(warehousing);
        return AjaxResult.success("查询库存中是否含有该产品型号批次的信息", warehousings);
    }

    /**
     * 新增保存入库信息
     */
    @RequiresPermissions("business:procurement:add")
    @Log(title = "新增保存", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@RequestBody ProcurementOrder procurementOrder) {
        if (procurementOrder.getProcurementModelList() == null) {
            return AjaxResult.error("请选择需要入库的产品");
        }
        String procurementWarehousingName = procurementOrder.getProcurementWarehousingName();
        Long saleGoodsId = procurementOrder.getSaleGoodsId();
        Long companyId = SecurityUtils.getLoginUser().getUser().getCompanyId();
        HashMap<String, Object> map = new HashMap<>();
        map.put("saleGoodsId", saleGoodsId);
        map.put("procurementWarehousingName", procurementWarehousingName);
        map.put("companyId", companyId);
        ProcurementOrder procurementOrder1 = procurementServer.selectProcurementByMap(map);
        if (procurementOrder1 != null) {
            //使用SimpleDateFormat的parse()方法生成Date
            SimpleDateFormat a = new SimpleDateFormat("yyyy-MM-dd");
            Date dates = null;
            try {
                dates = a.parse(a.format(procurementOrder.getProcurementWarehousingDate()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            String s = purchaseOrderService.orderNum(dates, 6);
            procurementOrder.setProcurementWarehousingName(s);
        }
        return toAjax(procurementServer.insertProcurementOrder(procurementOrder));
    }

    /**
     * 删除入库信息
     */
    @RequiresPermissions("business:procurement:remove")
    @Log(title = "删除入库信息", businessType = BusinessType.DELETE)
    @GetMapping("/remove/{procurementWarehousingId}")
    @ResponseBody
    public AjaxResult remove(@PathVariable("procurementWarehousingId") Long procurementWarehousingId) {
        procurementServer.deleteProcurementModel(procurementWarehousingId);
        return toAjax(1);
    }

    /**
     * 点击修改查询入库的信息
     */
    @GetMapping("/selectEedit/{procurementWarehousingId}")
    public Map<String, Object> selectEdit(@PathVariable("procurementWarehousingId") Long procurementWarehousingId) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("supplier", userService.selectSupplierById(sysUser.getCompanyId()));
        Company company = companyMapper.selectByCompanyId(sysUser.getCompanyId());
        resMap.put("user", userService.selectSalesmanList(sysUser.getCompanyId()));
        resMap.put("taxRate", company.getTaxRate());
        ProcurementOrder procurementOrders = new ProcurementOrder();
        procurementOrders.setProcurementWarehousingId(procurementWarehousingId);
        procurementOrders.setDeptId(sysUser.getCompanyId());
        //查询产品入库信息
        ProcurementOrder procurementOrder1 = procurementServer.selectProcurementBy(procurementOrders);
        //产品入库子集属性
        List<ProcurementModel> procurementModels = procurementServer.selectProcurementModelById(procurementWarehousingId);
        if (procurementServer.selectProcurementModelById(procurementWarehousingId).size() != 0) {
            resMap.put("procurementOrder", procurementOrder1);
        } else {
//            procurementOrder1.setProcurementModelList(procurementModels);
            resMap.put("procurementOrder", procurementOrder1);
        }

        // 获取上一条临近的ID
        resMap.put("previousId", procurementServer.querypreviousId(procurementWarehousingId));
        // 获取下一条临近的ID
        resMap.put("nextId", procurementServer.queryNextId(procurementWarehousingId));
        return resMap;
    }

    /**
     * 修改保存产品信息
     */
    @RequiresPermissions("business:procurement:edit")
    @Log(title = "修改保存", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@RequestBody ProcurementOrder procurementOrder) {
        if (procurementOrder.getProcurementModelList() == null) {
            return AjaxResult.error("请选择需要入库的产品");
        }
        int s = procurementServer.updateProcurementOrder(procurementOrder);
        if (s == 1) {
            return AjaxResult.success("修改成功");
        } else {
            return AjaxResult.error("产品的医疗器械注册证不唯一，请重新输入！");
        }
    }

    @GetMapping("/selectProductModelLists")
    @ResponseBody
    public TableDataInfo selectProductModelLists(@RequestParam(value = "productName", required = false) String productName,
                                                 @RequestParam(value = "productType", required = false) String productType) {

        Long deptId = SecurityUtils.getLoginUser().getUser().getCompanyId();
        Product product = new Product();
        product.setDeptId(deptId);
        product.setProductName(productName);
        product.setProductType(productType);
        startPage();
        return getDataTable(procurementServer.selectProductLists(product));
    }

    @PostMapping("/selectProductType")
    @ResponseBody
    public List<Integer> selectProductType(HttpServletRequest request) {
        String productType = request.getParameter("productType");
        return procurementServer.selectProductType(productType);
    }

    /**
     * 查询供应商的绑定业务员
     */
    @GetMapping("/selectUser/{companyId}")
    @ResponseBody
    public AjaxResult selectUser(@PathVariable("companyId") Long companyId) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Map<String, Object> map = new HashMap<>();
        map.put("deptId", sysUser.getCompanyId());
        map.put("companyId", companyId);
        CompanyOther companyOther = iCompanyOtherServer.selectByCompanyIdAndDeptId(map);
        if (companyOther != null) {
            return AjaxResult.success(companyOther);
        } else {
            return AjaxResult.error("该公司没有合作单位请设置负责人信息");
        }
    }
}
